# from flask import Flask,request
# app = Flask(__name__)

# @app.route('/')
# def index():
# 	return '<h1>home</h1>'

# @app.route('/user/<name>')
# def user(name):
# 	return '<h1>hello,%s</h1>'%name

# if __name__ == '__main__':
# 	app.run(debug=True)
import os

from flask import Flask, render_template, session, redirect, url_for
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import Form
from wtforms import StringField, SubmitField, PasswordField
from wtforms.validators import DataRequired, Length

# from flask_mail import Mail, current_app, Message

basedir = os.path.abspath(os.path.dirname(__file__))
app = Flask(__name__)
# form
app.config['SECRET_KEY'] = 'hard to guess string'
# sql
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'data2.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True

bootstrap = Bootstrap(app)
db = SQLAlchemy(app)


# mail = Mail(app)

#
# def send_email(to, subject, template, **kwargs):
#     msg = Message(app.config['FLASKY_MAIL_SUBJECT_PREFIX'] + subject, sender=app.config['FLASKY_MAIL_SENDER'],
#                   recipients=[to])
#     msg.body = render_template(template + '.txt', **kwargs)
#     msg.html = render_template(template + '.html', **kwargs)
#     mail.send(msg)

class User(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), unique=True, index=True)
    userword = db.Column(db.String(64), unique=True, index=True)
    score = db.Column(db.Integer, default='0')

    def __repr__(self):
        return '<User %r>' % self.username


class NameForm(Form):
    name = StringField('what is your name?', validators={DataRequired()})
    userpwd = PasswordField("password", validators={DataRequired(), Length(min=11, max=12)})
    submit = SubmitField(u'登录')


@app.route('/', methods=['GET', 'POST'])
def index():
    form = NameForm()
    name = session.get('name')
    score = 1
    if name is not None:
        user = User.query.filter_by(username=session.get('name')).first()
        score = user.score
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.name.data).first()
        if user is None:
            session['known'] = False
            session['name'] = "用户名或密码错误！"
        else:
            if user.userword == form.userpwd.data:
                session['known'] = True
                session['name'] = form.name.data
                score = user.score
            else:
                session['known'] = False
                session['name'] = "用户名或密码错误！"
        return redirect(url_for('index'))
    if score == 1:
        score = 0
    posts = User.query.order_by(User.score.desc()).all()
    return render_template('index.html', form=form, name=session.get('name'),
                           known=session.get('known', False), posts=posts, score=score)


@app.route('/<score>')
def twoindex(score):
    name = session.get('name')
    user = User.query.filter_by(username=name).first()
    if len(score) < 4:
        user.score = int(score)
    db.session.commit()
    posts = User.query.order_by(User.score.desc()).all()
    return render_template('index.html', name=session.get('name'),
                           known=session.get('known', True), posts=posts, score=user.score)


@app.route('/jianren/<name>')
def youxi(name):
    user = User.query.filter_by(username=str(name)).first()
    return render_template("jianren.html", user=user)


@app.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404


@app.errorhandler(500)
def internal_server_error(e):
    return render_template('500.html'), 500


if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', threaded=True)
